package com.lc.zpyh.ui.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.SelectMerchantsCanteenApi;
import com.lc.zpyh.http.request.SelectMerchantsFlApi;
import com.lc.zpyh.http.response.SelectMerchantsFlBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.mine.LoginCodeActivity;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

public class SelectMerchantsFlActivity extends AppActivity {
    @BindView(R.id.rl_title_bar)
    TitleBar rlTitleBar;
    @BindView(R.id.rv_supermarket)
    RecyclerView rvSupermarket;
    @BindView(R.id.layout_refresh)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.ll_inTheEnd)
    LinearLayout llInTheEnd;
    private String flid;
    private String title;
    private String schoolid;
    private BaseQuickAdapter<SelectMerchantsFlBean.ListBean, BaseViewHolder> adapter;
    private List<SelectMerchantsFlBean.ListBean> dataBeanList =new ArrayList<>();
    private String canteenId;
    private int page = 1;
    private int total=1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_selectmerchantsfl;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        flid = getIntent().getStringExtra("flid");
        title = getIntent().getStringExtra("title");
        schoolid = getIntent().getStringExtra("schoolid");
        canteenId = getIntent().getStringExtra("canteenId");
        rlTitleBar.setTitle(title);
        Log.e("TAG", "onCreate: "+canteenId +"-- "+flid);
        if (flid.equals("0")){

            selectMerchantsCanteen(page,schoolid,canteenId);
        }
        if (canteenId.equals("0")){
            setUpAdapter(page,schoolid,flid);
        }

        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                if (flid.equals("0")){

                    selectMerchantsCanteen(page,schoolid,canteenId);
                }
                if (canteenId.equals("0")){
                    setUpAdapter(page,schoolid,flid);
                }
                refreshLayout.finishRefreshing();

            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                refreshLayout.finishLoadmore();
//                if (!TextUtils.isEmpty(goods_classify_id)) {



                if (dataBeanList.size() < total) {
                    page++;
                    if (flid.equals("0")){

                        selectMerchantsCanteen(page,schoolid,canteenId);
                    }
                    if (canteenId.equals("0")){
                        setUpAdapter(page,schoolid,flid);
                    }
                } else {
                    refreshLayout.setEnableLoadmore(false);
                    llInTheEnd.setVisibility(View.VISIBLE);
                }
//         }
            }
        });
    }

    private void selectMerchantsCanteen(int page, String schoolid, String canteenId) {
        EasyHttp.post(this)
                .api(new SelectMerchantsCanteenApi().setSchoolid(schoolid).setPageNum(page+"").setPageSize("999").setCanteenId(canteenId)).request(new HttpCallback<SelectMerchantsFlBean>(this) {

            @Override
            public void onSucceed(SelectMerchantsFlBean data) {
                if (data.getCode()==0){

                    if (adapter==null) {
                        dataBeanList.clear();
                        dataBeanList.addAll(data.getList());

                        adapter = new BaseQuickAdapter<SelectMerchantsFlBean.ListBean, BaseViewHolder>
                                (R.layout.item_shop_goods, dataBeanList) {

                            @Override
                            protected void convert(BaseViewHolder baseViewHolder, SelectMerchantsFlBean.ListBean dataBean) {
                                if (dataBean.getMerchantCoupons() != null ) {
                                    if (dataBean.getMerchantCoupons().size() > 0 && dataBean.getMerchantCoupons().size() < 2) {

                                        baseViewHolder.setText(R.id.tv_tag_type1, "满"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getMeetTheConditions()+"","100",0)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, false);
                                    } else if (dataBean.getMerchantCoupons().size() >= 2) {
                                        baseViewHolder.setText(R.id.tv_tag_type1, "满"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getMeetTheConditions()+"","100",2)+"减"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setText(R.id.tv_tag_type2, "满"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(1).getMeetTheConditions()+"","100",2)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(1).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, true);
                                    }
                                } else {
                                    baseViewHolder.setVisible(R.id.tv_tag_type1, false);
                                }
                                baseViewHolder.setText(R.id.tv_shop_name, dataBean.getName());
                                if (dataBean.getStatus()==0){
                                    baseViewHolder.setGone(R.id.tv_status,true);
                                }else {
                                    baseViewHolder.setVisible(R.id.tv_status,true);
                                }

                                if (dataBean.getImg() != null) {
                                    GlideApp.with(SelectMerchantsFlActivity.this).load(IntentKey.ORDER_IMAGE+dataBean.getImg()).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01)).into((ImageView) baseViewHolder.getView(R.id.img_shop));

                                }
                                baseViewHolder.setText(R.id.tv_xiaoliang, "月销量"+dataBean.getSales());

                            }


                        };

                        View emptyview = View.inflate(SelectMerchantsFlActivity.this, R.layout.empty_emptylayout, null);
                        adapter.setEmptyView(emptyview);
                        rvSupermarket.setAdapter(adapter);
                        adapter.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {

                                if (!CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(), IntentKey.USERID,""))){
                                    startActivity(LoginCodeActivity.class);
                                    return;
                                }
                                startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",dataBeanList.get(position).getId()+""));
                            }
                        });
                    }else {
                        if (page!=1) {
                            dataBeanList.addAll(data.getList());
                            adapter.notifyDataSetChanged();
                        }else {
                            dataBeanList.clear();
                            dataBeanList.addAll(data.getList());
                            adapter.notifyDataSetChanged();
                            llInTheEnd.setVisibility(View.GONE);
                        }

                    }
                    if (dataBeanList.size()>0) {
                        refreshLayout.setEnableLoadmore(true);
                        llInTheEnd.setVisibility(View.GONE);
                    } else {
                        refreshLayout.setEnableLoadmore(false);
                        View emptyview = View.inflate(getContext(), R.layout.empty_emptylayout, null);
                        adapter.setEmptyView(emptyview);
                        llInTheEnd.setVisibility(View.VISIBLE);
                    }
                }


            }
            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });


    }

    private void setUpAdapter(int page,String schoolId,String flid) {

        EasyHttp.post(this)
                .api(new SelectMerchantsFlApi().setSchoolid(schoolId).setPageNum(page+"").setPageSize("999").setFlid(flid)).request(new HttpCallback<SelectMerchantsFlBean>(this) {

            @Override
            public void onSucceed(SelectMerchantsFlBean data) {
                if (data.getCode()==0){

                    if (adapter==null) {
                        dataBeanList.clear();
                        dataBeanList.addAll(data.getList());

                        adapter = new BaseQuickAdapter<SelectMerchantsFlBean.ListBean, BaseViewHolder>
                                (R.layout.item_shop_goods, dataBeanList) {

                            @Override
                            protected void convert(BaseViewHolder baseViewHolder, SelectMerchantsFlBean.ListBean dataBean) {
                                if (dataBean.getMerchantCoupons() != null ) {
                                    if (dataBean.getMerchantCoupons().size() > 0 && dataBean.getMerchantCoupons().size() < 2) {

                                        baseViewHolder.setText(R.id.tv_tag_type1, "满"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getMeetTheConditions()+"","100",0)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, false);
                                    } else if (dataBean.getMerchantCoupons().size() >= 2) {
                                        baseViewHolder.setText(R.id.tv_tag_type1, "满"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getMeetTheConditions()+"","100",2)+"减"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setText(R.id.tv_tag_type2, "满"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(1).getMeetTheConditions()+"","100",2)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(1).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, true);
                                    }
                                } else {
                                    baseViewHolder.setVisible(R.id.tv_tag_type1, false);
                                }
                                baseViewHolder.setText(R.id.tv_shop_name, dataBean.getName());

                                if (dataBean.getImg() != null) {
                                    GlideApp.with(SelectMerchantsFlActivity.this).load(IntentKey.ORDER_IMAGE+dataBean.getImg()).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01)).into((ImageView) baseViewHolder.getView(R.id.img_shop));

                                }
                                baseViewHolder.setText(R.id.tv_xiaoliang, "月销量"+dataBean.getSales());

                            }


                        };

                        View emptyview = View.inflate(SelectMerchantsFlActivity.this, R.layout.empty_emptylayout, null);
                        adapter.setEmptyView(emptyview);
                        rvSupermarket.setAdapter(adapter);
                        adapter.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {

                                if (!CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(), IntentKey.USERID,""))){
                                    startActivity(LoginCodeActivity.class);
                                    return;
                                }
                                startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",dataBeanList.get(position).getId()+""));
                            }
                        });
                    }else {
                        if (page!=1) {
                            dataBeanList.addAll(data.getList());
                            adapter.notifyDataSetChanged();
                        }else {
                            dataBeanList.clear();
                            dataBeanList.addAll(data.getList());
                            adapter.notifyDataSetChanged();
                            llInTheEnd.setVisibility(View.GONE);
                        }

                    }
                    if (dataBeanList.size()>0) {
                        refreshLayout.setEnableLoadmore(true);
                        llInTheEnd.setVisibility(View.GONE);
                    } else {
                        refreshLayout.setEnableLoadmore(false);
                        View emptyview = View.inflate(getContext(), R.layout.empty_emptylayout, null);
                        adapter.setEmptyView(emptyview);
                        llInTheEnd.setVisibility(View.VISIBLE);
                    }
                }


            }
            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });






    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode()== EvenConstant.PAYSTAUTS){

            finish();
        }
    }
}
